package com.sxwl.auth.netty;

import com.sxwl.auth.config.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @author reading
 * @Description TODO
 * @Date 2020/4/12 21:07
 */
@Service(value = "nettyServer")
@Slf4j
public class ChatServer {
    private static EventLoopGroup bossGroup = new NioEventLoopGroup();
    private static EventLoopGroup workGroup = new NioEventLoopGroup();
    private static ServerBootstrap serverBootstrap = new ServerBootstrap();
    @Autowired
    private NettyProperties nettyProperties;
    public  void start(){
        log.info("netty start");
        try {
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebsocketInitializer());
            ChannelFuture channelFuture = serverBootstrap.bind(nettyProperties.getPort()).sync();
            System.out.println("Service started");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
